import React, { useState, useEffect } from 'react';
import {
    Box,
    Container,
    Typography,
    Grid,
    Fab,
    Button,
    Paper,
    Alert,
    CircularProgress,
    TextField,
    InputAdornment,
    Menu,
    MenuItem,
    ListItemIcon,
    ListItemText,
} from '@mui/material';
import {
    Add as AddIcon,
    Refresh as RefreshIcon,
    Search as SearchIcon,
    ViewInAr as ModelIcon,
    Category as GeometryIcon
} from '@mui/icons-material';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';

import { useModelContext } from '../contexts/ModelContext';
import ModelCard from '../components/ModelCard';
import ConfirmDialog from '../components/ui/ConfirmDialog';

const ModelList = () => {
    const navigate = useNavigate();
    const {
        models,
        loading: contextLoading,
        error,
        fetchModels,
        deleteModel
    } = useModelContext();

    const [searchTerm, setSearchTerm] = useState('');
    const [filteredModels, setFilteredModels] = useState([]);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [selectedModelId, setSelectedModelId] = useState(null);
    const [addMenuAnchor, setAddMenuAnchor] = useState(null);
    const [deleteError, setDeleteError] = useState(null);
    const [loading, setLoading] = useState(false);
    const [fabMenuAnchor, setFabMenuAnchor] = useState(null);

    // Filter models when search term or models change
    useEffect(() => {
        if (!models) return;

        if (!searchTerm.trim()) {
            setFilteredModels(models);
            return;
        }

        const filtered = models.filter(model =>
            model.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (model.description && model.description.toLowerCase().includes(searchTerm.toLowerCase()))
        );

        setFilteredModels(filtered);
    }, [searchTerm, models]);

    const handleAddMenuOpen = (event) => {
        setAddMenuAnchor(event.currentTarget);
    };

    const handleAddMenuClose = () => {
        setAddMenuAnchor(null);
    };

    const handleFabMenuOpen = (event) => {
        setFabMenuAnchor(event.currentTarget);
    };

    const handleFabMenuClose = () => {
        setFabMenuAnchor(null);
    };

    const handleCreateNew = () => {
        handleAddMenuClose();
        handleFabMenuClose();
        navigate('/models/create');
    };

    const handleCreateGeometry = () => {
        handleAddMenuClose();
        handleFabMenuClose();
        navigate('/models/geometry/create');
    };

    const handleRefresh = () => {
        fetchModels();
    };

    const handleDeleteClick = (modelId) => {
        console.log('准备删除模型ID:', modelId, '类型:', typeof modelId);

        if (!modelId) {
            console.error('删除操作缺少有效的模型ID');
            return;
        }

        // 确认ID格式正确
        if (typeof modelId !== 'string' && typeof modelId !== 'number') {
            console.error('模型ID类型不正确，应为字符串或数字:', modelId, typeof modelId);
            return;
        }

        setSelectedModelId(modelId);
        setDeleteDialogOpen(true);
    };

    const handleConfirmDelete = async () => {
        if (!selectedModelId) {
            console.error('删除操作缺少模型ID');
            return;
        }

        console.log('确认删除模型ID:', selectedModelId);
        setLoading(true);
        setDeleteError(null);

        try {
            await deleteModel(selectedModelId);
            console.log('模型删除成功:', selectedModelId);
            setDeleteDialogOpen(false);
            setSelectedModelId(null);
            // 刷新模型列表
            fetchModels();
        } catch (err) {
            console.error('删除模型时出错:', err);
            setDeleteError(err.message || '删除模型失败，请稍后再试');
        } finally {
            setLoading(false);
        }
    };

    const handleCancelDelete = () => {
        setDeleteDialogOpen(false);
        setSelectedModelId(null);
    };

    return (
        <Container maxWidth="xl" sx={{ py: 4 }}>
            <Paper
                component={motion.div}
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
                elevation={0}
                sx={{
                    p: 4,
                    backgroundImage: 'linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%)',
                    borderRadius: 4,
                    mb: 4
                }}
            >
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                    <Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 700 }}>
                        3D模型管理
                    </Typography>
                    <Box>
                        <Button
                            variant="contained"
                            color="primary"
                            onClick={handleRefresh}
                            startIcon={<RefreshIcon />}
                            sx={{ mr: 2 }}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                            disabled={contextLoading || loading}
                        >
                            刷新
                        </Button>
                        <Button
                            variant="contained"
                            color="secondary"
                            onClick={handleAddMenuOpen}
                            startIcon={<AddIcon />}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                        >
                            创建模型
                        </Button>
                        <Menu
                            anchorEl={addMenuAnchor}
                            open={Boolean(addMenuAnchor)}
                            onClose={handleAddMenuClose}
                        >
                            <MenuItem onClick={handleCreateNew}>
                                <ListItemIcon>
                                    <ModelIcon fontSize="small" />
                                </ListItemIcon>
                                <ListItemText>上传模型文件</ListItemText>
                            </MenuItem>
                            <MenuItem onClick={handleCreateGeometry}>
                                <ListItemIcon>
                                    <GeometryIcon fontSize="small" />
                                </ListItemIcon>
                                <ListItemText>创建几何体模型</ListItemText>
                            </MenuItem>
                        </Menu>
                    </Box>
                </Box>
                <Typography variant="body1" color="text.secondary" paragraph>
                    管理您的3D模型库，创建、编辑和删除模型
                </Typography>
            </Paper>

            {error && (
                <Alert severity="error" sx={{ mb: 4 }}>
                    {error}
                </Alert>
            )}

            <Box sx={{ mb: 4 }}>
                <TextField
                    fullWidth
                    placeholder="搜索模型..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    InputProps={{
                        startAdornment: (
                            <InputAdornment position="start">
                                <SearchIcon />
                            </InputAdornment>
                        ),
                    }}
                    variant="outlined"
                    sx={{
                        backgroundColor: 'white',
                        borderRadius: 2,
                        '& .MuiOutlinedInput-root': {
                            borderRadius: 2,
                        }
                    }}
                />
            </Box>

            {(contextLoading || loading) ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', p: 8 }}>
                    <CircularProgress />
                </Box>
            ) : (
                <>
                    {filteredModels.length > 0 ? (
                        <Grid container spacing={3}>
                            {filteredModels.map((model) => (
                                <Grid item xs={12} sm={6} md={4} lg={3} key={model.id}>
                                    <ModelCard model={model} onDelete={handleDeleteClick} />
                                </Grid>
                            ))}
                        </Grid>
                    ) : (
                        <Paper
                            sx={{
                                p: 4,
                                textAlign: 'center',
                                borderRadius: 2,
                                backgroundColor: '#f5f5f5'
                            }}
                        >
                            <Typography variant="h6" color="text.secondary" gutterBottom>
                                {searchTerm ? '没有找到匹配的模型' : '没有可用的模型'}
                            </Typography>
                            <Typography variant="body2" color="text.secondary">
                                {searchTerm ? '尝试使用其他搜索词' : '点击"创建模型"按钮来添加您的第一个模型'}
                            </Typography>
                        </Paper>
                    )}
                </>
            )}

            {/* 悬浮添加按钮 */}
            <Fab
                color="secondary"
                aria-label="add"
                sx={{
                    position: 'fixed',
                    bottom: 32,
                    right: 32,
                    zIndex: 1000
                }}
                onClick={handleFabMenuOpen}
                component={motion.button}
                whileHover={{ scale: 1.1, rotate: 180 }}
                whileTap={{ scale: 0.9 }}
                transition={{ type: 'spring', stiffness: 400, damping: 10 }}
            >
                <AddIcon />
            </Fab>

            <Menu
                anchorEl={fabMenuAnchor}
                open={Boolean(fabMenuAnchor)}
                onClose={handleFabMenuClose}
            >
                <MenuItem onClick={handleCreateNew}>
                    <ListItemIcon>
                        <ModelIcon fontSize="small" />
                    </ListItemIcon>
                    <ListItemText>上传模型文件</ListItemText>
                </MenuItem>
                <MenuItem onClick={handleCreateGeometry}>
                    <ListItemIcon>
                        <GeometryIcon fontSize="small" />
                    </ListItemIcon>
                    <ListItemText>创建几何体模型</ListItemText>
                </MenuItem>
            </Menu>

            {/* 删除确认对话框 */}
            <ConfirmDialog
                open={deleteDialogOpen}
                title="确认删除"
                content="您确定要删除这个模型吗？此操作不可撤销。"
                onConfirm={handleConfirmDelete}
                onCancel={handleCancelDelete}
                confirmLoading={loading}
                error={deleteError}
            />
        </Container>
    );
};

export default ModelList;